package org.chen.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.bao.bean.UserRegisterB;
import org.bao.utils.MyUtils;
import org.chen.service.impl.UserLoginServiceImpl;

/**
 * 账号登录的部分
 */
@WebServlet("/UserLoginAction")
public class UserLoginAction extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置request编码
		request.setCharacterEncoding("utf-8");

		// 取出客户端发送的表单数据
		// 将表单数据存入实体bean中进行传输
		UserRegisterB userB = MyUtils.convertFormData2Bean(request, UserRegisterB.class);
		System.out.println("userB:" + userB);

		// 调用model层进行业务逻辑处理：查询数据库进行用户信息合法性验证
		List<UserRegisterB> lstUsers = MyUtils.getInstance(UserLoginServiceImpl.class).queryLoginInfo(userB);

		System.out.println("lstUsers:" + lstUsers);

		if (lstUsers != null && lstUsers.size() > 0) {
//				// 登陆成功，跳转到登录成功的页面
//				// 缓存登陆成功的用户信息
//				request.getSession().setAttribute("loginedUser",lstUsers.get(0));
//				// 使用重定向
////				response.sendRedirect("homepage.jsp");
//				response.setContentType("text/html;charset=utf-8");
//				PrintWriter out=response.getWriter();
//				out.print("<script language='javascript'>alert('登录成功！');"
//						+ "var index = parent.layer.getFrameIndex(window.name);parent.layer.close(index);"
//						+ "window.open('homepage.jsp','_parent');</script>");
			request.getSession().setAttribute("userTel", userB.getUsertel());
			request.getSession().setAttribute("userName", lstUsers.get(0).getUsername());
			request.getSession().setAttribute("userSex", lstUsers.get(0).getUsersex());
			request.getSession().setAttribute("userLocation", lstUsers.get(0).getUserlocation());

			PrintWriter pw = response.getWriter();
			pw.write("1");
			pw.flush();

		} else {
//				// 登录失败，重新登录
//				// 使用重定向
////				response.sendRedirect("userlogin_1.jsp");
//				response.setContentType("text/html;charset=utf-8");
//				PrintWriter out=response.getWriter();
//				out.print("<script language='javascript'>alert('登录失败，请重新输入！');window.location.href='userlogin_1.jsp';</script>");

			PrintWriter pw = response.getWriter();
			pw.write("0");
			pw.flush();

		}

	}

}
